<template>
  <div id="mapContainer">
    <div class="panel">
      <el-button @click="handleDrawRadiationCircle">绘制辐射圈</el-button>
      <el-button @click="changeColor">修改辐射圈颜色</el-button>
      <el-button @click="removeRadiationCircle">移除辐射圈</el-button>
      <el-button @click="addRadiationCircle">再添加一个</el-button>
      <el-button @click="addGradientPolygon">渐变圆</el-button>
    </div>
  </div>
</template>
<script setup>
import { Map, View } from "ol";
import { fromLonLat, get } from "ol/proj";

import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import Feature from "ol/feature";
import { Point, LineString, Polygon, Circle } from "ol/geom";
import {
  Style,
  Stroke,
  Fill,
  Circle as CircleStyle,
  Icon,
  Text,
} from "ol/style";

import GeoJSON from "ol/format/GeoJSON.js";

import * as turf from "@turf/turf";
import * as radash from "radash";

import { onMounted, nextTick, ref } from "vue";

import { tdt_api_key /** 天地图的key */ } from "@/config/keys.json";
import { addTdtBaseLayer } from "@/utils/baseMap.js";

import { getLayerByName } from "@/utils/layer.js";

import { flyTo } from "../../utils/view";
import { drawRadiationCircle } from "../../utils/feature";
import { remove } from "ol/array";
import { add } from "ol/coordinate";

function initMap() {
  const map = new Map({
    view: new View({
      //   center: fromLonLat([114.5, 31]),
      projection: "EPSG:4326",
      center: [114.5, 31],
      zoom: 9,
    }),
    target: "mapContainer",
    controls: [],
  });

  // 加载底图
  addTdtBaseLayer(map, tdt_api_key, "img", "c", "wmts");
  window.map = map;
}

onMounted(() => {
  nextTick(() => {
    initMap();
  });
});

let handler,
  id = "112";

function handleDrawRadiationCircle() {
  handler = drawRadiationCircle(
    window.map,
    [
      {
        id,
        coordinate: [114.5, 31],
      },
    ],
    100,
    "blue",
    3,
    0.5
  );

  return;

  const position = [114.5, 31]; // 辐射圈的位置

  const feature = new Feature({
    geometry: new Point(position),
  });

  const layer = new VectorLayer({
    source: new VectorSource({
      features: [feature],
    }),
  });

  window.map.addLayer(layer);

  const getRadiationStyle = (radiusQueue, color = "rgba(255, 0, 0, 0.8)") => {
    return [
      ...radiusQueue.map((radius, index) => {
        return new Style({
          image: new CircleStyle({
            radius,
            // fill: new Fill({
            //   color,
            // }),
            stroke: new Stroke({
              color,
              width: 5,
            }),
          }),
        });
      }),
    ];
  };

  let maxRadius = 100; // 辐射圈的半径
  const speed = 1; // 辐射圈的速度
  const rippleNumber = 3; // 辐射圈的个数

  // 辐射圈队列
  const queue = [0];
  layer.setStyle(getRadiationStyle(queue));

  layer.on("postrender", () => {
    if (queue[0] >= maxRadius) {
      queue.shift();
    }

    if (
      queue[queue.length - 1] >= maxRadius / rippleNumber &&
      queue.length < rippleNumber
    ) {
      queue.push(0);
    }

    queue.forEach((el, index) => {
      queue[index] += speed;
    });

    layer.setStyle(getRadiationStyle(queue));
  });
}

function changeColor() {
  console.log(handler.get("color"));
  handler.set("color", "red");
}

function removeRadiationCircle() {
  handler.remove(id);
}

function addRadiationCircle() {
  handler.set("color", "green");
  handler.set("speed", 0.3);

  const position = [114.2, 31]; // 辐射圈的位置

  handler.add([
    {
      id: "113",
      coordinate: position,
    },
  ]);
}

function addGradientPolygon() {
  const position = [
    [114.2, 31],
    [114.8, 31],
    [114.8, 31.2],
    [114.2, 31.2],
    [114.2, 31],
  ];
  const vectorLayer = new VectorLayer({
    source: new VectorSource({
      features: [
        new Feature({
          geometry: new Polygon([position]),
        }),
      ],
    }),
    style: (feature, resolution) => {
      // 自定义样式函数
      return [
        new Style({
          renderer: function (coordinate, state) {
            let arr = coordinate[0]
            const ctx = state.context;

            // 创建线性渐变（从左上到右下）
            const gradient = ctx.createLinearGradient(...arr[0],...arr[2]); // 坐标系为 Canvas 相对坐标

            // 添加颜色断点
            gradient.addColorStop(0, "rgba(0, 0, 255, 0.8)"); // 起始颜色（蓝色）
            gradient.addColorStop(1, "rgba(0, 255, 0, 0.8)"); // 结束颜色（绿色）

            ctx.fillStyle = gradient;
            // ctx.fillStyle = "rgba(255, 0, 0, 0.8)";
            ctx.strokeStyle = "red";

            ctx.beginPath();
            // let arr = option.coodArr || [];
            for (let i = 0; i < arr.length; i++) {
              const data = arr[i];
              if (i === 0) {
                ctx.moveTo(data[0], data[1]);
              } else {
                ctx.lineTo(data[0], data[1]);
              }
            }
            ctx.closePath();
            ctx.fill();
            ctx.stroke();
          },
        }),
      ];
    },
  });

  // 将图层添加到地图
  window.map.addLayer(vectorLayer);
}
</script>

<style scoped>
#mapContainer {
  width: 100%;
  height: 99vh;
}

.panel {
  position: absolute;
  top: 10px;
  left: 150px;
  z-index: 999;
}
</style>
